package servidor.principal.control;

import java.rmi.server.UnicastRemoteObject;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.jdo.Extent;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;


import servidor.dominio.Categoria;
import servidor.dominio.Cliente;
import servidor.dominio.Comerciante;
import servidor.dominio.Concepto;

import servidor.dominio.Empleado;

import servidor.principal.control.*;
import servidor.principal.assembler.*;

import comun.dto.*;
import comun.iControl.*;


public class ControlEmpleado extends UnicastRemoteObject implements IControlEmpleado{ 

	public ControlEmpleado() throws Exception{ 
	}


	/**
	 *
	 */

	public boolean addEmpleadoDTO(EmpleadoDTO pDTO,String cuitEmpresa,String cat, Vector<Concepto> con) throws Exception{
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		try{
			tx.begin();
			//recupero el cliente al cual pertenece el empleado a agregar 

			String filter = "cuit == \""+cuitEmpresa+"\""; 
			String filter2= "nombre==\""+cat+"\"";
			//String filter3 = "descripcion == \""+con.get(0).getDescripcion()+"\""; 
			//ver si modificamos en vez de collection usar hashset
			//Collection<Concepto> conceptos= new Collection<Concepto>();


			Cliente cliente = (Cliente)this.getObject(pm, Cliente.class, filter);
			Categoria categoria=(Categoria)this.getObject(pm, Categoria.class, filter2); 

			//conceptos.add(concepto);
			EmpleadoAssembler emplAssembler = new EmpleadoAssembler();
			Empleado empl= emplAssembler.getEmpleado(pDTO);

			empl.setCliente(cliente); 
			empl.setCategoria(categoria);

			//Agrego Conceptos
			Set conceptos = new HashSet();
			for(int i =0;i< con.size();i++){
				Concepto concept = (Concepto) con.get(i);

				Concepto concep = new Concepto();
				concep.setEmpleados(empl);
				concep.setImporte(concept.getImporte());
				concep.setPorcentaje(concept.getPorcentaje());
				concep.setRemunerativo(concept.getRemunerativo());
				concep.setTipo(concept.getTipo());
				//setCuitEmpresa(empl.getCuit());
				concep.setDescripcion(concept.getDescripcion());

				pm.makePersistent(concep);
				//empl.setConcepto(concept);
				//this.persistencia.cargarObjetoPersistente(concep);
				conceptos.add(concep);
			}

			empl.setConceptos(conceptos);
			pDTO=emplAssembler.getEmpleadoDTO(empl);
			pm.makePersistent(empl);
			tx.commit();
			System.out.println("Empleado dado de alta. OK");
		}
		finally
		{
			if (tx.isActive())
			{
				tx.rollback();
			}
			pm.close();
		} 
		return true;

	}



	public boolean existeEmpleado(String cuil)throws Exception{
		//ver como filtrar por cuil y nombre de la empresa a la que pertenece
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();	        
		boolean existe = false;
		try {

			if (!tx.isActive())tx.begin();
			String filter = "cuil == \""+cuil+"\"";
			Collection empleadoCol= this.getObjects(pm,Empleado.class,filter);
			if (empleadoCol.size()>=1) 
				existe=true;

			try {
				tx.commit(); 
			} catch (RuntimeException e) {
				e.printStackTrace();
				return false;
			}
		} finally {


			if (tx.isActive()) tx.rollback();
		}
		return existe;


	}

	public boolean existeEmpresa(String cuit)throws Exception{
		//ver como filtrar por cuil y nombre de la empresa a la que pertenece
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();	        
		boolean existe = false;
		try {

			if (!tx.isActive())tx.begin();
			String filter = "cuit == \""+cuit+"\"";
			Collection empleadoCol= this.getObjects(pm,Cliente.class,filter);
			if (empleadoCol.size()>=1) 
				existe=true;

			try {
				tx.commit(); 
			} catch (RuntimeException e) {
				e.printStackTrace();
				return false;
			}
		} finally {


			if (tx.isActive()) tx.rollback();
		}
		return existe;


	}

	public void eliminarEmpleado(String cuil) throws Exception{
		// eliminar todos los datos de empleado tmb
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		try {
			tx.begin();
			if (!tx.isActive())tx.begin();   
			Empleado empleado = new Empleado();
			String filter = "cuil == \""+cuil+"\"";
			empleado= (Empleado) this.getObject(pm,Empleado.class,filter);      
			//elimina los conceptos
//			Collection con=empleado.getConceptos();
/*			for (Iterator i = con.iterator(); i.hasNext(); ) {
				Concepto concepto= (Concepto) i.next();
				pm.deletePersistent(concepto);

			}*/
			pm.deletePersistent(empleado);
			tx.commit();
			System.out.println("Empleado Eliminado. OK");

			//this.persistencia.borrarObjeto(cliente);
			//this.persistencia.cierraTrans();


		}	
		finally
		{
			if (tx.isActive())
			{
				tx.rollback();
			}
			pm.close();
		} 

	}

	public boolean existeEmpleadoNombre(String nombre) throws Exception{
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		boolean existe = false;
		try {

			if (!tx.isActive())tx.begin();
			String filter = "nombre == \""+nombre+"\"";
			Collection empleadoCol= this.getObjects(pm,Empleado.class,filter);
			if (empleadoCol.size()>=1) 
				existe=true;

			try {
				tx.commit(); 
			} catch (RuntimeException e) {
				e.printStackTrace();
				return false;
			}
		} finally {


			if (tx.isActive()) tx.rollback();
		}
		return existe;
	}

	public void modificarEmpleado(EmpleadoDTO c) throws Exception{
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		
		String filter2= "nombre==\""+c.getCat()+"\"";
		try {
			//this.persistencia.AbreTrans();
			tx.begin();
			Categoria categoria=(Categoria)this.getObject(pm, Categoria.class, filter2); 
			
			
			if (!tx.isActive())tx.begin(); 
			String filter = "cuil == \""+c.getCuil()+"\"";
			Empleado empleado= (Empleado) this.getObject(pm,Empleado.class,filter);
			empleado.setNombre(c.getNombre());
			empleado.setApellido(c.getApellido());
			empleado.setCategoria(categoria);
			empleado.setCat(c.getCat());
			empleado.setFechaIngreso(c.getFechaIngreso());
//			empleado.setConceptos(c.getConceptos());

			tx.commit();
			System.out.println("Empleado Modificado. OK");

		}	
		finally
		{
			if (tx.isActive())
			{
				tx.rollback();
			}
			pm.close();
		} 

	}



	public Vector<EmpleadoDTO> getEmpleados(String cuit) throws Exception {
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		Vector<EmpleadoDTO> vector = new Vector<EmpleadoDTO>();
		Collection<Empleado> consultaCol = null;       

		try {
			if (!tx.isActive())tx.begin();
			String filter = "cuitEmpresa == \""+cuit+"\"";
			consultaCol= this.getObjects(pm,Empleado.class,filter);
			Iterator<Empleado> iter = consultaCol.iterator();
			while (iter.hasNext()) {
				Empleado empl = iter.next();
				EmpleadoDTO emplDTO = EmpleadoAssembler.getEmpleadoDTO(empl);
				vector.add(emplDTO);
			}            
			tx.commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive()) tx.rollback();
		}
		return vector;
	}

	public Vector<EmpleadoDTO> getEmpleados() throws Exception {
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		Vector<EmpleadoDTO> vector = new Vector<EmpleadoDTO>();
		Collection<Empleado> consultaCol = null;       

		try {
			if (!tx.isActive())tx.begin();
			//String filter = "cuitEmpresa == \""+cuit+"\"";
			consultaCol= this.getObjects(pm,Empleado.class,null);
			Iterator<Empleado> iter = consultaCol.iterator();
			while (iter.hasNext()) {
				Empleado empl = iter.next();
				EmpleadoDTO emplDTO = EmpleadoAssembler.getEmpleadoDTO(empl);
				vector.add(emplDTO);
			}            
			tx.commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive()) tx.rollback();
		}
		return vector;
	}



	public Vector<EmpleadoDTO> getEmpleadosCuil(String cuil)throws Exception{
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		Vector<EmpleadoDTO> vector = new Vector<EmpleadoDTO>();
		Collection<Empleado> consultaCol = null;       

		try {
			if (!tx.isActive())tx.begin();
			String filter = "cuil == \""+cuil+"\"";
			consultaCol= this.getObjects(pm,Empleado.class,filter);
			Iterator<Empleado> iter = consultaCol.iterator();
			while (iter.hasNext()) {
				Empleado empl = iter.next();
				EmpleadoDTO emplDTO = EmpleadoAssembler.getEmpleadoDTO(empl);
				vector.add(emplDTO);
			}            
			tx.commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive()) tx.rollback();
		}

		return vector;

	}

	public boolean existeRelacion(Vector<EmpleadoDTO> empleado, String cuil) throws Exception{
		int i=0;
		boolean  existe=false;
		try{
			while ((!empleado.isEmpty())||(existe!=true)){		
				if (empleado.get(0).getCuil().equals((Object)cuil)){
					existe=true;
				}
				empleado.remove(0);
			}
		}catch(Exception e){

		}
		return existe;
	}






	public Collection getObjects(PersistenceManager pm, Class clase,String filter)throws Exception{
		Collection retorno=null;
		try{
			Class empleadoClass = clase;
			Extent clnEmpleado=pm.getExtent(empleadoClass, false); 
			Query query = pm.newQuery(clnEmpleado,filter);
			retorno=(Collection)query.execute();
		} catch(Exception e) {
			throw e;
		}
		return retorno;
	}

	public Object getObject(PersistenceManager pm,Class clase,String filter) throws Exception{
		Object objetoPersistente = null;
		try {

			Extent clnObject = pm.getExtent(clase, true);
			Query query = pm.newQuery(clnObject,filter);
			Collection objetos = (Collection)query.execute();


			Object[] prueba = objetos.toArray();
			if(prueba.length > 0){
				objetoPersistente = prueba[0];
			}	
		}
		catch (Exception ex) {
			ex.printStackTrace();
			throw ex;           
		}
		return objetoPersistente;
	}


}
